package com.wty.cmims.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wty.cmims.pojo.Code;
import com.wty.cmims.pojo.MedicalHistory;
import com.wty.cmims.pojo.Medication;
import com.wty.cmims.pojo.Prescription;
import com.wty.cmims.pojo.ResponseResult;
import com.wty.cmims.service.MedicalHistoryService;
import com.wty.cmims.service.MedicationService;
import com.wty.cmims.service.PrescriptionService;
import com.wty.cmims.mapper.PrescriptionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
* @author wty
* @description 针对表【prescription】的数据库操作Service实现
* @createDate 2024-12-16 22:13:49
*/
@Service
public class PrescriptionServiceImpl extends ServiceImpl<PrescriptionMapper, Prescription>
    implements PrescriptionService{
    @Autowired
    MedicalHistoryService medicalHistoryService;
    @Autowired
    MedicationService medicationService;
    @Override
    @Transactional
    public ResponseResult<Map<String, Object>> prescriptionFindAddOrUpdate(Map<String, Object> paramsMap) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        LambdaQueryWrapper<Prescription> wrapperExist = new LambdaQueryWrapper<>();
        wrapperExist.eq(Prescription::getHistoryId, paramsMap.get("historyId"));
        Prescription exist = this.getOne(wrapperExist);
        if (exist != null){
            // 修改处方
            exist.setMedications((String) paramsMap.get("medications"));
            boolean update = this.updateById(exist);
            if (update){
                responseResult.setCode(Code.SUCCESS);
                responseResult.setMessage("修改处方成功");
            } else {
                responseResult.setCode(Code.ERROR);
                responseResult.setMessage("修改处方失败");
            }
            return responseResult;
        }
        // 根据historyId在病历表查找residentId和appointmentId
        LambdaQueryWrapper<MedicalHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MedicalHistory::getId, paramsMap.get("historyId"));
        MedicalHistory medicalHistory = medicalHistoryService.getOne(wrapper);
        paramsMap.put("residentId", medicalHistory.getResidentId());
        paramsMap.put("appointmentId", medicalHistory.getAppointmentId());
        Prescription prescription = new Prescription();
        prescription.setAppointmentId((Integer) paramsMap.get("appointmentId"));
        prescription.setHistoryId(Integer.parseInt((String) paramsMap.get("historyId")));
        prescription.setResidentId((Integer) paramsMap.get("residentId"));
        prescription.setInstitutionId((Integer) paramsMap.get("institutionId"));
        prescription.setDepartmentId((Integer) paramsMap.get("departmentId"));
        prescription.setDoctorId((Integer) paramsMap.get("doctorId"));
        prescription.setMedications((String) paramsMap.get("medications"));

        SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy/MM/dd");
        Date date = null;
        try {
            if (paramsMap.get("make_date") != null){
                date = sdfDay.parse(paramsMap.get("make_date").toString());
            }
        } catch (ParseException e) {
            System.out.println("日期转换错误");
        }
        if (date != null) {
            paramsMap.put("make_date", date);
        }

        prescription.setMakeDate((Date) paramsMap.get("make_date"));

        boolean save = this.save(prescription);
        if (save) {
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("生成处方成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("生成处方失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Map<String, Object>> prescriptionFindByHistoryId(Integer historyId) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        LambdaQueryWrapper<Prescription> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Prescription::getHistoryId, historyId);
        Prescription prescription = this.getOne(wrapper);

        List<Map<String, Object>> medicationsArray = new ArrayList<>();
        if (prescription != null){
            // 取出medications
            String medications = prescription.getMedications();
            // 分割为若干个“id*count”
            String[] split = medications.split(",");
            Set<Integer> medicationIds = new HashSet<>();
            Map<Integer, String> idToNumMap = new HashMap<>();

            for (String s : split) {
                // 取出一个“id*count”，分割为id和count
                String[] item = s.split("\\*");
                int id = Integer.parseInt(item[0]);
                medicationIds.add(id);
                idToNumMap.put(id, item[1]);
            }

            // 批量查询药品信息
            List<Medication> medicationsList = medicationService.listByIds(medicationIds);
            for (Medication medication : medicationsList) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", medication.getId());
                map.put("name", medication.getName());
                map.put("indications", medication.getIndications());
                map.put("price", medication.getPrice());
                map.put("specification", medication.getSpecification());
                map.put("unit", medication.getUnit());
                map.put("dosage", medication.getDosage());
                map.put("precautions", medication.getPrecautions());
                map.put("adverse_effects", medication.getAdverseEffects());
                map.put("expiration_date", medication.getExpirationDate());
                map.put("is_otc", medication.getIsOtc());
                map.put("manufacturer", medication.getManufacturer());
                map.put("approval_number", medication.getApprovalNumber());
                map.put("medication_img", medication.getMedicationImg());
                map.put("is_del", medication.getIsDel());
                map.put("count", Integer.parseInt(idToNumMap.get(medication.getId())));
                medicationsArray.add(map);
            }
        }
        if (!medicationsArray.isEmpty()){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("存在处方");
            responseResult.setDatas(medicationsArray);
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("不存在处方");
        }
        return responseResult;
    }
}